package com.orangecy.completablefuture;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author : orangeCy.奕
 * @Time : 2021/10/6
 * @desc : 猎豹养成产品源码
 */
public class CtfDemo {

    public static void main(String[] args) {
        //有一批价格单id （1,2,3,4,5）
        //supplySync函数的使用
        List<Integer> resList = Stream.of(1, 2, 3, 4, 5)
                //从db 获取价格
                .map(index -> CompletableFuture.supplyAsync(() -> queryPrice(index)))
                //method reference
                //处理折扣价
                .map(f -> f.thenApply(CtfDemo::discountPrice))
                //汇聚
                .map(CompletableFuture::join)
                .collect(Collectors.toList());
        resList.forEach(System.out::println);

        System.out.println("=================");
        //thenCompose方法
        CompletableFuture.supplyAsync(() -> 1).thenCompose(i -> CompletableFuture.supplyAsync(() -> i + 1))
                .thenAccept(System.out::println);
        System.out.println("=================");

        //thenCombine
        CompletableFuture.supplyAsync(() -> 1).thenCombine(CompletableFuture.supplyAsync(() ->2),
                (r1,r2) -> (r1 + r2) * 3).thenAccept(System.out::println);
        System.out.println("=================");
        //thenAcceptBoth
        CompletableFuture.supplyAsync(() -> 1).thenAcceptBoth(CompletableFuture.supplyAsync(() -> 4),
                (r1,r2) -> System.out.println(r1+r2*5));
        System.out.println("=================");

        //liebao grow join
        System.out.println(Stream.of(CompletableFuture.supplyAsync(() ->"liebao"),
                CompletableFuture.supplyAsync(() -> "grow"))
                .map(CompletableFuture::join)
                .collect(Collectors.joining(" "))
        );

    }

    public static Integer queryPrice(Integer dbId) {
        return dbId + 10;
    }

    public static  Integer discountPrice(Integer price) {
        return price - 3 > 0 ? price -3 : 0;
    }
}